<template>
    <form-item
        :designer="designer" 
        :field="field" 
        :rules="state.rules"
    >
        <el-radio-group 
            v-model="formModel[field.options.name]"
            :size="size"
            :disabled="disabled"
            :class="{
                'display-block':props.field.options.displayStyle==='block',
                'add-mr-5':props.field.options.displayStyle ==='block' && props.field.options.border
            }"
        >
            <template v-if="field.options.buttonStyle">
                <el-radio-button 
                    v-for="item in field.options.optionItems" 
                    :key="item.value" 
                    :value="item.value" 
                    :label="item.label" 
                />
            </template>
            <template v-else>
                <el-radio 
                    v-for="item in field.options.optionItems" 
                    :key="item.value" 
                    :value="item.value"
                    :border="border"
                >
                    {{ item.label }}
                </el-radio>
            </template>
        </el-radio-group>
    </form-item>
</template>

<script setup>
import {nextTick, onMounted, reactive,computed} from 'vue';
import FormItem from './form-item.vue';
import {useRules} from '@/hooks/useRules.js'

defineOptions({
    name:"xy-radio"
})

const props = defineProps({
    designer:{
        type:Object,
        default:()=>({})
    },
    field:{
        type:Object,
        default:()=>({})
    },
    formModel:{
        type:Object,
        default:()=>({})
    }
})

const state = reactive(({
    fieldVal:"",
    rules:[]
}))

useRules(state,props.field)

const disabled = computed(()=>{
    return props.field.options.disabled
})

const size = computed(()=>{
    return props.field.options.size || 'default'
})

const border = computed(()=>{
    return props.field.options.border
})

const setFieldVal = val=>{
    props.formModel[props.field.options.name] = val
}

onMounted(()=>{
    if(props.field && props.field.options.defaultValue){
        // 存在默认值的情况下进行初始化
        setFieldVal(props.field.options.defaultValue)
    }

    nextTick(()=>{
        if(!props.designer) return
        props.designer.createFieldValFun(props.field.id, setFieldVal)
    })
})
</script>

<style lang="scss" scoped>
.display-block{
    display: block;
    label{
        display: block
    }
}
.add-mr-5{
    label{
        &:last-child{
            margin-right: 30px;
        }
    }
}
</style>
